<template>
  <div id="users">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-input placeholder="请输入内容" class="search-input" v-model="searchText" @keydown.enter.native="initList">
          <el-button slot="append" icon="el-icon-search" @click="initList"></el-button>
        </el-input>
        <el-button type="success" plain class="add" @click="addDialogFormVisible=true">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table class="margin-20" :data="userList" border style="width:100%"  v-loading="loading">
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="role_name" label="权限">
      </el-table-column>
      <el-table-column label="用户状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="setStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="editUser(scope.row)"></el-button>
          <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="deleteDialog(scope.row)"></el-button>
          <el-button size="mini" type="warning" plain icon="el-icon-check" @click="GrantDialog(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[1, 2, 3, 4]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" label-width="80px" :rules="rules" ref="addUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" label-width="80px" :rules="rules" ref="editUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off" :disabled='true'></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit('editUserForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" label-width="120px">
        <el-form-item label="当前用户">
          <el-tag type="info">{{grantForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="请选择角色">
          <el-select v-model="roleId" placeholder="请选择角色">
            <el-option v-for="(role,index) in roleList" :key="index" :label="role.roleName" :value="role.id"></el-option>

          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantUserSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import {
  getUsers,
  setUserStatus,
  addUsers,
  editUsersId,
  deleteUser,
  getRoleList,
  grantUserRole
} from "../../login";
export default {
  data() {
    return {
      userList: [],
      searchText: "",
      currentPage: 1,
      pageSize: 3,
      total: 1,
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      grantDialogFormVisible: false,
      grantForm: {},
      roleList: [],
      roleId: "",
      loading: true,
      editForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        id: 0
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入电话", trigger: "blur" }]
      }
    };
  },
  created() {
    this.initList();
  },
  methods: {
    grantUserSubmit() {
      if (!this.roleId) {
        this.$message({
          type: "warning",
          message: "角色不能为空"
        });
      } else {
        grantUserRole({ id: this.grantForm.id, rid: this.roleId }).then(res => {
          if (res.meta.status === 200) {
            this.$message({
              type: "success",
              message: "设置角色成功"
            });
            this.grantDialogFormVisible = false;
            this.initList();
          } else {
            this.$message({
              type: "error",
              message: res.meta.msg
            });
          }
        });
      }
    },
    GrantDialog(row) {
      this.grantForm = row;
      this.grantDialogFormVisible = true;
      getRoleList().then(res => {
        console.log(res);
        if (res.meta.status === 200) {
          this.roleList = res.data;
        }
      });
    },
    deleteDialog(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteUser(row.id).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.initList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    editSubmit(formName) {
      this.$refs[formName].validate(valide => {
        if (valide) {
          editUsersId(this.editForm).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: "success",
                message: "编辑成功"
              });
              this.editDialogFormVisible = false;
              this.initList();
            }
          });
        }
      });
    },
    editUser(row) {
      this.editDialogFormVisible = true;
      this.editForm.username = row.username;
      this.editForm.email = row.email;
      this.editForm.mobile = row.mobile;
      this.editForm.id = row.id;
    },
    addSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addUsers(this.addForm).then(res => {
            console.log(res);
            if (res.meta.status == 201) {
              this.$message({
                message: res.meta.msg,
                type: "success"
              });
              this.addDialogFormVisible = false;
              this.initList();
            } else {
              this.$message({
                message: res.meta.msg,
                type: "warning"
              });
            }
          });
        }
      });
    },
    setStatus(row) {
      setUserStatus({ uid: row.id, type: row.mg_state }).then(res => {
        if (res.meta.status == 200) {
          this.$message({
            message: res.meta.msg,
            type: "success"
          });
        } else {
          this.$message({
            message: res.meta.msg,
            type: "warning"
          });
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.initList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.initList();
    },
    initList() {
      getUsers({
        params: {
          query: this.searchText,
          pagenum: this.currentPage,
          pagesize: this.pageSize
        }
      }).then(res => {
        console.log(res);
        this.total = res.data.total;
        this.userList = res.data.users;
        this.loading=false
      });
    }
  }
};
</script>
<style lang="scss" scoped>
#users {
  .search-input {
    width: 300px;
    margin-bottom: 20px;
  }
  .add {
    margin-left: 5px;
  }
  .page {
    margin-top: 20px;
    background-color: #d3dce6;
  }
}
</style>

